#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash Python-3.7.6.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

if [[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]]; then echo "请输入正确的构建路径"; exit 1; fi
if [[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]]; then echo "请输入正确的安装路径"; exit 1; fi

buildpath=$1
installpath=$2
if [[ "$1" =~ .*/$ ]]; then buildpath=${buildpath%/*}; fi
if [[ "$2" =~ .*/$ ]]; then installpath=${installpath%/*}; fi
if [[ "$buildpath" = "$installpath" ]]; then echo "构建路径和安装路径相同，请重新输入"; exit 1; fi

set -e
yum install -y gcc make wget openssl openssl-devel readline readline-devel zlib* libffi-devel tar
yum install -y zlib-devel bzip2-devel ncurses-devel sqlite-devel tk-devel gdbm-devel xz-devel

wget -t 0 -c -P $buildpath https://www.python.org/ftp/python/3.7.6/Python-3.7.6.tgz
tar -xvf $buildpath/Python-3.7.6.tgz -C $buildpath && rm -rf $buildpath/Python-3.7.6.tgz
cd $buildpath/Python-3.7.6
./configure --prefix=$installpath/python3 CC=clang CXX=clang++ FC=flang
make -j$(nproc)
make install

cat>"$installpath/python3/python3_modulefiles"<<EOF
#%Module1.0
conflict python3
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set PYTHON \$pwd
setenv PYTHON \$PYTHON
prepend-path PATH \$PYTHON/bin
prepend-path LD_LIBRARY_PATH \$PYTHON/lib
EOF

